package org.aplikator.client.shared.rpc.marshaller;

import org.aplikator.client.shared.descriptor.ActionDTO;
import org.aplikator.client.shared.descriptor.MenuDTO;
import org.jboss.errai.marshalling.client.api.MarshallingSession;
import org.jboss.errai.marshalling.client.api.annotations.ClientMarshaller;
import org.jboss.errai.marshalling.client.api.annotations.ServerMarshaller;
import org.jboss.errai.marshalling.client.api.json.EJObject;
import org.jboss.errai.marshalling.client.api.json.EJValue;
import org.jboss.errai.marshalling.client.marshallers.AbstractNullableMarshaller;

import java.util.List;

import static org.aplikator.client.shared.rpc.marshaller.DemarshallingUtils.clientDescriptorBaseUnMarshall;
import static org.aplikator.client.shared.rpc.marshaller.DemarshallingUtils.listUnMarshall;
import static org.aplikator.client.shared.rpc.marshaller.MarshallingUtils.listMarshall;

@ClientMarshaller(MenuDTO.class)
@ServerMarshaller(MenuDTO.class)
public class MenuDTOMarshaller extends AbstractNullableMarshaller<MenuDTO> {

	/*@Override
	public Class<MenuDTO> getTypeHandled() {
		return MenuDTO.class;
	}*/

	@Override
	public MenuDTO[] getEmptyArray() {
		return new MenuDTO[0];
	}
	
	@Override
	public MenuDTO doNotNullDemarshall(EJValue o, MarshallingSession ctx) {
		if (o.isObject() != null) {
			EJObject object = o.isObject();
			MenuDTO mdto = new MenuDTO();
			clientDescriptorBaseUnMarshall(object, mdto);
			List list = listUnMarshall(object.get("actions"), ctx, ActionDTO.class.getName());
			
			for (Object ob : list) {
				mdto.addAction((ActionDTO) ob);
			}

			return mdto;
		} else return null;
	}

	@Override
	public String doNotNullMarshall(MenuDTO o, MarshallingSession ctx) {
		StringBuilder builder = new StringBuilder("{");
		MarshallingUtils.clientDescriptorBase(builder, o).append(',');
		
		MarshallingUtils.key("actions", builder).append(':');
		listMarshall(builder, o.getActions(), ctx, ActionDTO.class.getName());
		
		builder.append("}");
		return builder.toString();
	}
}				

